/**
 * 编辑器配置工具类
 * 用于获取wangeditor的配置
 */

interface EditorSettings {
  uploadUrl: string;
  token: string;
}

/**
 * 从localStorage获取编辑器设置
 */
export function getEditorSettings(): EditorSettings {
  const defaultSettings: EditorSettings = {
    uploadUrl: '',
    token: ''
  };

  const settings = localStorage.getItem('editor-settings');
  if (!settings) {
    return defaultSettings;
  }

  try {
    const parsedSettings = JSON.parse(settings);
    return {
      uploadUrl: parsedSettings.uploadUrl || defaultSettings.uploadUrl,
      token: parsedSettings.token || defaultSettings.token
    };
  } catch (error) {
    console.error('Failed to parse editor settings:', error);
    return defaultSettings;
  }
}

/**
 * 获取wangeditor的配置
 * @param callback 自定义处理回调函数，用于处理自定义配置
 */
export function getWangEditorConfig(callback?: (settings: EditorSettings) => any) {
  const settings = getEditorSettings();
  
  // 基础配置
  const config = {
    // 如果设置了上传URL，启用上传功能
    MENU_CONF: {} as Record<string, any>
  };

  // 配置上传接口
  if (settings.uploadUrl) {
    // 配置图片上传
    config.MENU_CONF['uploadImage'] = {
      server: settings.uploadUrl,
      headers: settings.token ? {
        Authorization: settings.token,
      } : undefined,
    };

    // 配置视频上传
    config.MENU_CONF['uploadVideo'] = {
      server: settings.uploadUrl,
      headers: settings.token ? {
        Authorization: settings.token,
      } : undefined,
    };
  } else {
    // 如果没有配置上传URL，使用本地存储和回显
    // 配置图片上传
    config.MENU_CONF['uploadImage'] = {
      // 自定义上传
      customUpload: (file: File, insertFn: (url: string, alt: string, href: string) => void) => {
        // 将图片转换为Base64
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          // 获取Base64编码
          const base64 = reader.result as string;
          // 将Base64数据保存到localStorage中
          const imageKey = `noted_image_${Date.now()}`;
          localStorage.setItem(imageKey, base64);
          // 插入图片
          insertFn(base64, file.name, '');
        };
        reader.onerror = () => {
          console.error('图片读取失败');
        };
      }
    };

    // 配置视频上传
    config.MENU_CONF['uploadVideo'] = {
      // 自定义上传
      customUpload: (file: File, insertFn: (url: string, poster: string) => void) => {
        // 将视频转换为Base64
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          // 获取Base64编码
          const base64 = reader.result as string;
          // 将Base64数据保存到localStorage中
          const videoKey = `noted_video_${Date.now()}`;
          localStorage.setItem(videoKey, base64);
          // 插入视频
          insertFn(base64, '');
        };
        reader.onerror = () => {
          console.error('视频读取失败');
        };
      }
    };
  }

  // 如果有自定义处理回调，调用它
  if (callback) {
    return callback(settings) || config;
  }

  return config;
} 